<template>
  <view class="misc-outbound-container">
    <!-- 查询区域 -->
    <view class="query-section">
      <view class="query-header">
        <text class="query-title">查询出库单</text>
      </view>

      <!-- 查询输入区域 -->
      <view class="query-input-area">
        <view class="input-group">
          <text class="input-label">扫描出库单编号</text>
          <view class="input-wrapper">
            <input 
              class="query-input" 
              v-model="queryData.issueCode" 
              placeholder="请扫描或输入出库单编号"
              @confirm="handleIssueCodeConfirm"
            />
            <view class="input-icon scan-icon" @click="startScan">
              <uni-icons type="scan" size="16" color="#007AFF"></uni-icons>
            </view>
            <view class="input-icon clear-icon" @click="clearIssueCode">
              <uni-icons type="clear" size="16" color="#999"></uni-icons>
            </view>
          </view>
        </view>
      </view>
    </view>

    <!-- 其他出库单主表信息 -->
    <view class="misc-info-section" v-if="issueInfo">
      <view class="info-header">
        <text class="info-title">其他出库单信息</text>
        <view class="info-status" :class="getStatusClass(issueInfo.status)">
          {{ getStatusText(issueInfo.status) }}
        </view>
      </view>

      <view class="info-content">
        <view class="info-row">
          <text class="info-label">出库单号</text>
          <text class="info-value">{{ issueInfo.issueCode }}</text>
        </view>
        <view class="info-row">
          <text class="info-label">出库类型</text>
          <text class="info-value">{{ getMiscTypeText(issueInfo.miscType) }}</text>
        </view>
        <view class="info-row">
          <text class="info-label">出库日期</text>
          <text class="info-value">{{ issueInfo.issueDate || '-' }}</text>
        </view>
        <view class="info-row">
          <text class="info-label">备注</text>
          <text class="info-value">{{ issueInfo.remark || '-' }}</text>
        </view>
      </view>

    </view>

    <!-- 空状态提示 -->
    <view class="empty-state" v-if="issueInfo && issueLines.length === 0">
      <uni-icons type="info-filled" size="60" color="#ccc"></uni-icons>
      <text class="empty-text">该出库单暂无明细行</text>
    </view>
				
    <!-- 出库单行信息列表 -->
    <view class="misc-lines-section" v-if="issueLines.length > 0">
      <view class="section-header">
        <text class="section-title">出库明细行</text>
        <text class="section-count">共 {{ issueLines.length }} 行</text>
      </view>
      
      <view class="lines-list">
        <view 
          class="line-item" 
          v-for="line in issueLines" 
          :key="line.lineId"
          @click="enterLineDetail(line)"
        >
          <view class="line-header">
            <text class="line-title">物料信息</text>
            <view class="line-status" :class="getLineStatusClass(line)">
              {{ getLineStatusText(line) }}
            </view>
          </view>

          <view class="line-content">
            <view class="content-grid">
              <view class="grid-item">
                <text class="item-label">物料编码</text>
                <text class="item-value">{{ line.itemCode }}</text>
              </view>
              <view class="grid-item">
                <text class="item-label">物料名称</text>
                <text class="item-value">{{ line.itemName }}</text>
              </view>
              <view class="grid-item full-width">
                <text class="item-label">规格型号</text>
                <text class="item-value">{{ line.specification }}</text>
              </view>
              <view class="grid-item">
                <text class="item-label">单位</text>
                <text class="item-value">{{ line.unitName || '' }}</text>
              </view>
              <view class="grid-item">
                <text class="item-label">出库数量</text>
                <text class="item-value">{{ getActualIssuedQuantity(line) }}/{{ line.quantityIssue }}</text>
              </view>
              <view class="grid-item progress-item">
                <text class="item-label">出库进度</text>
                <view class="progress-info">
                  <view class="progress-bar">
                    <view 
                      class="progress-fill" 
                      :style="{ width: getProgressWidth(line) + '%' }"
                    ></view>
                  </view>
                  <text class="progress-text">{{ Math.round(getProgressWidth(line)) }}%</text>
                </view>
              </view>
            </view>
          </view>

          <view class="line-action">
            <uni-icons type="right" size="16" color="#999"></uni-icons>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
import { 
  initScan, 
  startScan as startPdaScan, 
  stopScan, 
  isPdaScanAvailable 
} from '@/utils/pdaScan.js'
import { getMiscIssueByCode, getMiscIssueByIssueId, getMiscIssueDetail } from '@/api/wm/miscissue.js'

export default {
  name: 'MiscOutbound',
  data() {
    return {
      queryData: {
        issueCode: '', // 出库单编号
        issueId: null  // 出库单ID
      },
      issueInfo: null,
      issueLines: [],
      executing: false
    }
  },
  
  computed: {
    canExecute() {
      // 只针对已审核的其他出库单显示执行按钮
      return this.issueInfo && this.issueInfo.status === 'APPROVED'
    }
  },
  
  mounted() {
    // 初始化PDA扫描监听（只初始化，不启动）
    if (isPdaScanAvailable()) {
      initScan(this.handlePdaScanResult, 'MiscOutbound')
    }
  },
  
  onShow() {
    // 页面显示时重新初始化并启动PDA扫描
    if (isPdaScanAvailable()) {
      initScan(this.handlePdaScanResult, 'MiscOutbound')
      startPdaScan('MiscOutbound')
    }
    // 页面显示时刷新数据（从detail页面返回时，或从待处理页面选择后）
    if (this.queryData.issueId) {
      this.refreshIssueById()
    }
  },
  
  onHide() {
    // 页面隐藏时停止PDA扫描，防止在详情页中误触发
    if (isPdaScanAvailable()) {
      stopScan('MiscOutbound')
    }
  },
  
  onUnload() {
    // 页面销毁时停止PDA扫描监听
    if (isPdaScanAvailable()) {
      stopScan('MiscOutbound')
    }
  },
  
  methods: {
    // 处理PDA扫描结果（广播扫描方式）
    handlePdaScanResult(code) {
      console.log('PDA扫描结果:', code)
      
      if (!code || !code.trim()) {
        console.log('扫描结果为空')
        return
      }
      
      const scanData = code.trim()
      
      // 设置出库单编号并自动执行查询
      this.queryData.issueCode = scanData
      this.handleIssueCodeConfirm()
    },
    
    // 清空出库单编号（只清空输入框，保留已查询的数据）
    clearIssueCode() {
      this.queryData.issueCode = ''
    },
    
    // 开始扫描（相机扫码方式）
    startScan() {
      uni.scanCode({
        onlyFromCamera: true,
        success: (res) => {
          this.queryData.issueCode = res.result
          this.handleIssueCodeConfirm()
        },
        fail: () => {
          uni.showToast({ title: '扫码失败', icon: 'none' })
        }
      })
    },
    
    // 处理出库单编号确认
    handleIssueCodeConfirm() {
      if (!this.queryData.issueCode.trim()) {
        uni.showToast({
          title: '出库单号为空，请检查！',
          icon: 'none'
        })
        return
      }
      
      this.queryIssueByCode()
    },
    
    // 根据出库单编号查询出库单（初始查询）
    queryIssueByCode() {
      if (!this.queryData.issueCode.trim()) {
        uni.showToast({ title: '请输入出库单编号', icon: 'none' })
        return
      }
      
      uni.showLoading({ title: '查询中...' })
      
      getMiscIssueByCode(this.queryData.issueCode).then(response => {
        const data = response.data
        this.issueInfo = data.miscIssue
        this.issueLines = data.issueLines || []
        
        // 查询成功后保存issueId，用于后续刷新
        if (this.issueInfo && this.issueInfo.issueId) {
          this.queryData.issueId = this.issueInfo.issueId
        }
             
      }).catch(error => {
        console.log('查询出库单失败:', error)
        if (error !== '500') {
          uni.showToast({
            title: '网络异常，请检查网络连接后重试', 
            icon: 'none',
            duration: 3000
          })
        }
        this.issueInfo = null
        this.issueLines = []
      }).finally(() => {
        this.clearIssueCode()
        uni.hideLoading()
      })
    },
    
    // 根据出库单ID刷新数据（后续查询）
    refreshIssueById() {
      if (!this.queryData.issueId) {
        return
      }
      
      getMiscIssueByIssueId(this.queryData.issueId).then(response => {
        const data = response.data
        this.issueInfo = data.miscIssue
        this.issueLines = data.issueLines || []
      }).catch(error => {
        console.log('刷新出库单失败:', error)
        if (error !== '500') {
          uni.showToast({
            title: '网络异常，请检查网络连接后重试', 
            icon: 'none',
            duration: 3000
          })
        }
        this.issueInfo = null
        this.issueLines = []
      })
    },
    
    // 进入行明细
    enterLineDetail(line) {
      if (!this.issueInfo) {
        uni.showToast({
          title: '请先查询出库单',
          icon: 'none'
        })
        return
      }
      
      // 根据出库单状态确定操作类型
      const optType = this.issueInfo.status === 'APPROVED' ? 'edit' : 'view'
      
      uni.navigateTo({
        url: `/pages/app/outbound/miscIssue/detail?issueCode=${this.issueInfo.issueCode}&issueId=${this.issueInfo.issueId}&lineId=${line.lineId}`,
        fail: (err) => {
          console.error('跳转到出库明细页面失败:', err)
          uni.showToast({
            title: '页面跳转失败',
            icon: 'none'
          })
        }
      })
    },
    
    // 获取状态文本
    getStatusText(status) {
      const map = {
        'PREPARE': '草稿',
        'APPROVED': '已审批',
        'COMPLETE': '已完成',
        'CANCELLED': '已取消'
      }
      return map[status] || status
    },
    
    // 获取状态样式
    getStatusClass(status) {
      const map = {
        'PREPARE': 'status-draft',
        'APPROVED': 'status-confirmed',
        'COMPLETE': 'status-completed',
        'CANCELLED': 'status-cancelled'
      }
      return map[status] || 'status-default'
    },
    
    // 获取出库类型文本
    getMiscTypeText(miscType) {
      const map = {
        '01': '其他出库',
        '02': '采购样品出库',
        '03': '客供出库',
        '04': '退料出库',
        '05': '盘盈出库',
        '06': '调拨出库',
        '07': '生产退料出库'
      }
      return map[miscType] || miscType || '未知类型'
    },
    
    // 获取行状态文本
    getLineStatusText(line) {
      const plannedQuantity = line.quantityIssue || 0
      const actualQuantity = this.getActualIssuedQuantity(line)
      
      if (actualQuantity === 0) {
        return '待出库'
      } else if (actualQuantity < plannedQuantity) {
        return '部分出库'
      } else {
        return '完全出库'
      }
    },
    
    // 获取行状态样式
    getLineStatusClass(line) {
      const plannedQuantity = line.quantityIssue || 0
      const actualQuantity = this.getActualIssuedQuantity(line)
      
      if (actualQuantity === 0) {
        return 'line-status-pending'
      } else if (actualQuantity < plannedQuantity) {
        return 'line-status-partial'
      } else {
        return 'line-status-completed'
      }
    },
    
    // 获取实际出库数量（明细总和）
    getActualIssuedQuantity(line) {
      if (!line.details || !Array.isArray(line.details)) {
        return 0
      }
      return line.details.reduce((total, detail) => {
        return total + (parseFloat(detail.quantity) || 0)
      }, 0)
    },
    
    // 获取进度宽度
    getProgressWidth(line) {
      const plannedQuantity = line.quantityIssue || 0
      const actualQuantity = this.getActualIssuedQuantity(line)
      if (plannedQuantity === 0) return 0
      return Math.min(100, (actualQuantity / plannedQuantity) * 100)
    },
    
    // 执行出库单
    executeRecpt() {
      if (!this.issueInfo || !this.issueInfo.issueId) {
        uni.showToast({
          title: '缺少出库单信息',
          icon: 'none'
        })
        return
      }
      
      // 确认执行
      uni.showModal({
        title: '确认执行',
        content: '确定要执行该出库单吗？执行后将完成出库操作。',
        success: (res) => {
          if (res.confirm) {
            this.performExecute()
          }
        }
      })
    },
    
    // 执行出库单操作
    performExecute() {
      if (this.executing) {
        return
      }
      
      this.executing = true
      uni.showLoading({ title: '执行中...' })
      
      executeMiscRecpt(this.issueInfo.issueId).then(response => {
        uni.showToast({
          title: '执行成功',
          icon: 'success'
        })
        
        // 执行成功后重新加载数据
        this.refreshIssueById()
        
      }).catch(error => {
        console.error('执行出库单失败:', error)
        
        // 检查是否是业务错误（code=500）
        if (error === '500') {
          // 拦截器已经显示了具体的业务错误信息，这里不需要再显示
          console.log('业务错误，拦截器已显示toast')
        } else {
          // 真正的网络异常
          uni.showToast({ 
            title: '网络异常，请检查网络连接后重试', 
            icon: 'none',
            duration: 3000
          })
        }
      }).finally(() => {
        this.executing = false
        uni.hideLoading()
      })
    },
    
    // 跳转到待处理列表页面
    goToPendingList() {
      uni.navigateTo({
        url: '/pages/app/inbound/miscRecpt/pending',
        fail: (err) => {
          console.error('跳转到待处理列表失败:', err)
          uni.showToast({
            title: '页面跳转失败',
            icon: 'none'
          })
        }
      })
    },
    
    // 设置选中的出库单（从pending页面返回时调用）
    setSelectedRecpt(issueId) {
      this.queryData.issueId = issueId
    }
  }
}
</script>

<style lang="scss" scoped>
.misc-outbound-container {
  padding: 20rpx;
  background: #f5f5f5;
  min-height: 100vh;
  padding-bottom: 120rpx;
}

.query-section {
  background: #fff;
  border-radius: 12rpx;
  padding: 30rpx;
  margin-bottom: 20rpx;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
}

.query-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20rpx;
  
  .query-title {
    font-size: 32rpx;
    font-weight: bold;
    color: #333;
  }
  
  .pending-btn {
    display: flex;
    align-items: center;
    gap: 8rpx;
    padding: 12rpx 20rpx;
    background: rgba(0, 122, 255, 0.1);
    border-radius: 20rpx;
    border: 1rpx solid rgba(0, 122, 255, 0.2);
    
    .btn-text {
      font-size: 24rpx;
      color: #007AFF;
      font-weight: 500;
    }
    
    &:active {
      background: rgba(0, 122, 255, 0.2);
      transform: scale(0.95);
    }
  }
}

.query-input-area {
  .input-group {
    .input-label {
	display: block;
      font-size: 26rpx;
		color: #333;
      margin-bottom: 15rpx;
}
	
	.input-wrapper {
		position: relative;
		display: flex;
		align-items: center;
		
		.query-input {
			flex: 1;
			height: 80rpx;
			padding: 0 100rpx 0 20rpx;
			border: 2rpx solid #e0e0e0;
			border-radius: 12rpx;
			font-size: 28rpx;
			background: #fff;
			
			&:focus {
				border-color: #007AFF;
			}
		}
		
		.input-icon {
			position: absolute;
			padding: 10rpx;
			border-radius: 50%;
			
			&.scan-icon {
				right: 60rpx;
          background: rgba(0, 122, 255, 0.08);
			}
			
			&.clear-icon {
				right: 16rpx;
			}
			}
		}
	}
}

.misc-info-section {
	background: #fff;
	border-radius: 12rpx;
	padding: 30rpx;
  margin-bottom: 20rpx;
	box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
}
	
.info-header, .section-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 20rpx;
		
  .info-title, .section-title {
			font-size: 32rpx;
			font-weight: bold;
			color: #333;
		}
		
		.info-status {
    padding: 6rpx 12rpx;
    border-radius: 16rpx;
    font-size: 20rpx;
    
    &.status-draft { background: #f8f9fa; color: #6c757d; }
    &.status-confirmed { background: #d1ecf1; color: #0c5460; }
    &.status-completed { background: #d4edda; color: #155724; }
    &.status-cancelled { background: #f8d7da; color: #721c24; }
  }
  
  .section-count {
    font-size: 24rpx;
    color: #666;
		}
	}
	
	.info-content {
		.info-row {
			display: flex;
    justify-content: space-between;
    padding: 12rpx 0;
    border-bottom: 1rpx solid #f0f0f0;
			
			&:last-child {
      border-bottom: none;
			}
			
    .info-label {
				font-size: 26rpx;
				color: #666;
      min-width: 140rpx;
			}
			
    .info-value {
      font-size: 26rpx;
      color: #333;
      flex: 1;
      text-align: right;
    }
  }
}

.action-section {
  margin-top: 20rpx;
  padding-top: 20rpx;
  border-top: 1rpx solid #f0f0f0;
  
  .action-btn {
		width: 100%;
		height: 80rpx;
    border-radius: 40rpx;
		display: flex;
		align-items: center;
		justify-content: center;
    gap: 10rpx;
		font-size: 28rpx;
    color: #fff;
		border: none;
    
    &.disabled {
				background: #ccc;
				color: #999;
				box-shadow: none;
    }
    
    .btn-text {
					font-size: 28rpx;
      font-weight: 600;
    }
    
    &.execute-btn {
      background: linear-gradient(135deg, #007bff 0%, #0056b3 100%);
      box-shadow: 0 4rpx 16rpx rgba(0, 123, 255, 0.3);
    }
  }
}

.empty-state {
				display: flex;
  flex-direction: column;
					align-items: center;
					justify-content: center;
  padding: 80rpx 40rpx;
						background: #fff;
  border-radius: 12rpx;
					margin-bottom: 20rpx;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
  
  .empty-text {
						font-size: 28rpx;
    color: #999;
    margin-top: 20rpx;
  }
}

// 行列表样式
.misc-lines-section {
  .lines-list {
	margin-top: 20rpx;

    .line-item {
	background: #fff;
	border-radius: 12rpx;
      margin-bottom: 20rpx;
      padding: 24rpx;
	box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
      transition: all 0.3s ease;
      position: relative;
      
      &:active {
        transform: scale(0.98);
        box-shadow: 0 1rpx 4rpx rgba(0, 0, 0, 0.15);
      }
      
      .line-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 20rpx;
		
        .line-title {
          font-size: 32rpx;
			font-weight: bold;
			color: #333;
		}
		
        .line-status {
          padding: 6rpx 12rpx;
          border-radius: 16rpx;
          font-size: 20rpx;
          
          &.line-status-pending {
            background: #fff3cd;
            color: #856404;
          }
          
          &.line-status-partial {
            background: #d1ecf1;
            color: #0c5460;
          }
          
          &.line-status-completed {
            background: #d4edda;
            color: #155724;
          }
        }
      }
      
      .line-content {
        padding-right: 60rpx;
        
        .content-grid {
          display: grid;
          grid-template-columns: 1fr 1fr;
          gap: 16rpx 20rpx;
          
          .grid-item {
			display: flex;
            flex-direction: column;
            
            .item-label {
					font-size: 22rpx;
			color: #666;
              margin-bottom: 6rpx;
            }
            
            .item-value {
              font-size: 24rpx;
				color: #333;
              font-weight: 500;
              word-break: break-all;
              line-height: 1.4;
            }
            
            &.full-width {
              grid-column: 1 / -1;
            }
            
            &.progress-item {
              grid-column: 1 / -1;
              
              .progress-info {
			display: flex;
                flex-direction: column;
                gap: 8rpx;
                
                .progress-bar {
                  height: 8rpx;
                  background: #e9ecef;
                  border-radius: 4rpx;
			overflow: hidden;
			
                  .progress-fill {
                    height: 100%;
                    background: linear-gradient(135deg, #28a745 0%, #20c997 100%);
                    border-radius: 4rpx;
                    transition: width 0.3s ease;
                  }
                }
                
                .progress-text {
				font-size: 22rpx;
                  color: #28a745;
			font-weight: bold;
						text-align: center;
					}
				}
			}
		}
	}
      }
      
      .line-action {
        position: absolute;
        right: 24rpx;
        top: 50%;
        transform: translateY(-50%);
      }
    }
  }
}
</style>
